package com.geekcoding.geekoj.repository;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.geekcoding.common.exceptions.GeekRuntimeException;
import com.geekcoding.geekoj.dto.User;
import com.geekcoding.geekoj.dto.request.UserChangePwdReq;
import com.geekcoding.geekoj.dto.request.UserSaveOrUpdateReq;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.mapper.UserEntityMapper;
import com.geekcoding.geekoj.utils.Json;
import lombok.NonNull;
import lombok.val;
import org.springframework.stereotype.Repository;

import java.util.Objects;
import java.util.Optional;

/**
 * @author xiaobai
 * @since 2024/02/25 14:16
 **/

@Repository
public class UserEntityRepository extends BaseRepository<UserEntity, User, UserEntityMapper> {

    @Override
    public User convert(UserEntity entity) {
        return Json.convert(entity, User.class);
    }

    public UserEntity findStuNo(String stuNo) {
//        baseMapper.selectOne(lambdaQuery().eq(UserEntity::getStuNo, stuNo))
//        return getOne(lambdaQuery().eq(UserEntity::getStuNo, stuNo));
        QueryWrapper<UserEntity> lambdaQueryWrapper = new QueryWrapper<>();
        lambdaQueryWrapper.eq("stu_no", stuNo);
//        lambdaQueryWrapper.eq(UserEntity::getStuNo, stuNo);
        return getOne(lambdaQueryWrapper);
    }

    public UserEntity addOrUpdate(UserSaveOrUpdateReq rpo) {
        UserEntity userEntity = Optional.ofNullable(rpo.getId()).map(this::getById).orElse(UserEntity.builder().build());
        if (Objects.isNull(userEntity)) {
            throw new GeekRuntimeException("用户不存在!");
        }
        if (StrUtil.isNotBlank(rpo.getCellphone())) {
            userEntity.setCellphone(rpo.getCellphone());
        }
        if (StrUtil.isNotBlank(rpo.getName())) {
            userEntity.setName(rpo.getName());
        }
        if (StrUtil.isNotBlank(rpo.getNickName())) {
            userEntity.setNickName(rpo.getNickName());
        }
        if (StrUtil.isNotBlank(rpo.getStuNo())) {
            userEntity.setStuNo(rpo.getStuNo());
        }
        Optional.ofNullable(rpo.getSex()).ifPresent(userEntity::setSex);
        Optional.ofNullable(rpo.getRole()).ifPresent(userEntity::setRole);
        userEntity.initPwd();
        saveOrUpdate(userEntity);
        return userEntity;
    }

    public void changePassword(@NonNull UserChangePwdReq req, @NonNull UserEntity user) {
        req.check();
        val password = SecureUtil.md5(req.getOldPassword() + user.getSalt());
        if (!password.equals(user.getPassword())) {
            throw new GeekRuntimeException("旧密码不正确");
        }
        user.setPassword(SecureUtil.md5(req.getPassword() + user.getSalt()));
        saveOrUpdate(user);
    }
}
